<template>
  <div class="section">
    <h2>Excel 导入</h2>
    <div class="import-controls">
      <input 
        type="file" 
        accept=".xlsx,.xls,.csv" 
        @change="handleFileChange"
      />
      <div v-if="message" :class="{'success': success, 'error': !success}">
        {{ message }}
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';

export default {
  props: {
    // 可接收自定义表头映射
    columnMap: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      message: '',
      success: false
    };
  },
  methods: {
    handleFileChange(e) {
      const file = e.target.files[0];
      if (!file) return;
      
      this.message = '正在处理文件...';
      this.success = false;
      
      const reader = new FileReader();
      reader.onload = (event) => {
        try {
          const data = new Uint8Array(event.target.result);
          const workbook = XLSX.read(data, { type: 'array' });
          
          // 获取第一个工作表
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          
          // 将工作表转换为 JSON 数据
          let jsonData = XLSX.utils.sheet_to_json(worksheet);
          
          // 应用表头映射（如果有）
          if (Object.keys(this.columnMap).length > 0) {
            jsonData = jsonData.map(row => {
              const newRow = {};
              for (const [oldKey, newKey] of Object.entries(this.columnMap)) {
                if (row.hasOwnProperty(oldKey)) {
                  newRow[newKey] = row[oldKey];
                }
              }
              return newRow;
            });
          }
          
          this.message = `成功导入 ${jsonData.length} 条数据`;
          this.success = true;
          
          // 发送成功事件，携带解析后的数据
          this.$emit('import-success', jsonData);
        } catch (error) {
          this.message = '文件解析失败，请检查文件格式';
          this.success = false;
          this.$emit('import-error', error);
        }
      };
      
      reader.onerror = (error) => {
        this.message = '文件读取失败';
        this.success = false;
        this.$emit('import-error', error);
      };
      
      reader.readAsArrayBuffer(file);
    }
  }
};
</script>
